package tree;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * 113. 路径总和II
 *
 * @author Api
 * @date 2023/10/24 0:21
 */
public class Code113_PathSummationII {
    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        public TreeNode() {
        }

        public TreeNode(int val) {
            this.val = val;
        }

        public TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    // 先序递归遍历
    public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
        List<List<Integer>> res = new ArrayList<>();
        if (root == null) {
            return res; // 非空判断
        }
        List<Integer> path = new LinkedList<>();
        preOrderDFS(root, targetSum, res, path);
        return res;
    }

    private void preOrderDFS(TreeNode root, int targetSum, List<List<Integer>> res, List<Integer> path) {
        path.add(root.val);
        // 遇到了叶子节点
        if (root.left == null && root.right == null) {
            // 找到了和为targetSum的路径
            if (targetSum - root.val == 0) {
                res.add(new ArrayList<>(path));
            }
            return; // 如果和不为 targetSum，返回
        }
        if (root.left != null) {
            preOrderDFS(root.left, targetSum - root.val, res, path);
            path.remove(path.size() - 1);
        }
        if (root.right != null) {
            preOrderDFS(root.right, targetSum - root.val, res, path);
            path.remove(path.size() - 1);
        }
    }

    // 解法2
    List<List<Integer>> result;
    LinkedList<Integer> path;

    public List<List<Integer>> pathSum1(TreeNode root, int targetSum) {
        result = new LinkedList<>();
        path = new LinkedList<>();
        traversal(root, targetSum);
        return result;
    }

    private void traversal(TreeNode root, int count) {
        if (root == null) {
            return;
        }
        path.offer(root.val);
        count -= root.val;
        if (root.left == null && root.right == null && count == 0) {
            result.add(new LinkedList<>(path));
        }
        traversal(root.left, count);
        traversal(root.right, count);
        path.removeLast();
    }
}
